package mblog.core.persist.service.impl;

import mblog.core.persist.dao.DocInfoDao;
import mblog.core.persist.entity.DocInfoPO;
import mblog.core.persist.service.DocInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Yu on 2017/9/26.
 */
@Service
@Transactional
public class DocInfoServiceImpl implements DocInfoService {
    @Autowired
    private DocInfoDao docInfoDao;


    @Override
    public Map<String,  List<DocInfoPO>> list() {
        List<DocInfoPO> list=docInfoDao.list();
        Map<String,  List<DocInfoPO>> map=null;
        try {
            map= groupByMenuid(list);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }

    @Override
    public DocInfoPO get(Long id) {
        return  docInfoDao.get(id);
    }

    @Override
    public void save(DocInfoPO docInfoPO) {

        docInfoDao.saveOrUpdate(docInfoPO);
    }

    @Override
    public void delete(Long id) {
        docInfoDao.deleteById(id);
    }

    /**
     * 按照menuid进行分组
     * @param list
     * @return
     * @throws Exception
     */
    private Map<String,  List<DocInfoPO>> groupByMenuid(List<DocInfoPO> list) throws Exception{
        Map<String, List<DocInfoPO>> resultMap = new HashMap<String, List<DocInfoPO>>();

        try{
            for(DocInfoPO docInfo : list){

                if(resultMap.containsKey(docInfo.getMenuid())){//map中已存在，
                    resultMap.get(docInfo.getMenuid()).add(docInfo);
                }else{//map中不存在，新建key，用来存放数据
                    List<DocInfoPO> tmpList = new ArrayList<DocInfoPO>();
                    tmpList.add(docInfo);
                    resultMap.put(docInfo.getMenuid(), tmpList);
                }

            }

        }catch(Exception e){
            throw new Exception("进行分组时出现异常", e);
        }

        return resultMap;
    }

}
